import {Component, OnInit, AfterViewInit, ViewChild} from '@angular/core';
import {Router, ActivatedRoute} from "@angular/router";
import {MsgResult} from "../../../models/msg-result";
import {OneDialogService} from "../../../widgets/one-dialog/one-dialog.service";
import {Path} from "../../../portal/admin/admin-breadcrumb/breadcrumb";
import {PageSubject} from "../../../util/page-subject";
import {OneOperationComponent} from "../../../widgets/one-operation/one-operation.component";
import {TableUtil} from "../../../util/table-util";
import {API, MsgConstants} from "../../../constants/constants";
import {TreeUtil} from "../../../util/tree-util";
import {ResponseUtil} from "../../../util/response-util";
import {Dictionary} from "./dictionary";
import {DictionarysService} from "./dictionarys.service";

declare var $;

@Component({
  selector: 'app-dictionarys',
  templateUrl: './dictionarys.component.html',
  styleUrls: ['./dictionarys.component.css']
})
export class DictionarysComponent implements OnInit,AfterViewInit {
  @ViewChild(OneOperationComponent) operation: OneOperationComponent;
  id :Array<string> =[];
  table;
  treeObj;
  dic :Dictionary;

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private tableUtil: TableUtil,
    private treeUtil: TreeUtil,
    private dictionaryService: DictionarysService,
    private pageSubject: PageSubject,
    private dialogService: OneDialogService,
    private responseUtil: ResponseUtil
  ) {

  }


  //按钮点击触及事件
  proxy = {
    //添加，修改，删除
    "add": () => this.add(),
    "update": () => this.update(),
    "dicDelete": () => this.dicDelete()
  }
  ngOnInit() {
    //初始化面包屑导航
    this.pushPage();
    //初始化表单
    this.loadDic();

    this.initDictionaryZTree();
  }


  ngAfterViewInit() {
    //操作函数代理
    this.operation.proxy = this.proxy;
  }

  /**
   * 面包屑导航
   */
  pushPage() {
    let path = new Path("数据字典", "");
    this.pageSubject.pushPage("数据字典", "查询", path);
  }

  search() {
    this.table.bootstrapTable('refresh');
  }

  loadDic(){
    this.table = this.tableUtil.load("one_table_dic",{
      columns: [
        {checkbox: true },
        {field: "id", title: 'ID', align: 'left', visible: false, switchable: false},
        {field: "code", title: '字典编码', align: 'left'},
        {field: "value", title: '值', align: 'right'},
        {field: "display", title: '字典名称', align: 'left'},
        {field: "describe", title: '描述', align: 'left'},
        {field: "orderNum", title: '顺序', align: 'right', sortName: "ORDERNUM", sortable: true},
        {field: "isUse", title: '启用', align: 'left', formatter: this.yesOrNoFormat}
      ],
      idField: "id",
      sidePagination: 'server',
      pagination: true,
      pageNumber: 1,
      pageSize: 15,
      pageList: [10,25, 50,100],
      paginationPreText: "上一页",
      paginationNextText: "下一页",
      paginationLoop: false,//是否开启循环分页
      singleSelect: false,//多选
      clickToSelect: true,//点击选中
      toolbar: "#one_operation_dictionarys",
      url: API.dPageListV2,
      method: 'post',
      //传递附加参数
      queryParams: (params) => {
        params.code = $("#dicCode").val();
        params.display = $("#dicDisplay").val();
        params.isUse = $("#isUse").val();
        params.pId =  $("#dicId").val();
        return params;
      },
      //返回数据处理器
      responseHandler: (result) => {
        return this.responseUtil.bsPageHandler(result, (result) => {
        });
      },
      height: 700,//table高度
      sortable: true,
      order: 'asc',
      sortName: 'ORDERNUM',
      // search:true,//是否显示搜索框
      // searchOnEnterKey:true,//点击enter键是否触发搜索事件
      // searchText:'',//默认搜索内容
      // smartDisplay:true,//智能显示分页或card视图
      showColumns: true,//显示自定义显示列按钮
      showRefresh: true,//显示刷新按钮
      minimumCountColumns: 3,//最少保留显示的列数量
      showToggle: true,//显示视图切换按钮
      showPaginationSwitch: true,//显示是否分页切换按钮
      classes: "table table-hover",
      striped: true,//隔行变色
      mobileResponsive: true//响应式
    });
    this.tableUtil.bindResetTableView(this.table);
  }

  /**
   * 初始化菜单树
   */
  initDictionaryZTree() {
    this.dictionaryService.treeDD().subscribe(
      result => this.responseUtil.success(result, this.processMenuTreeResult),
      message => this.responseUtil.error(message)
    );
  }
  private processMenuTreeResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.initDictionaryTree(result.data);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }
  initDictionaryTree(dics) {
    //初始化菜单树
    let setting = {
      callback: {
        onClick: this.clickTree
      },
      data: {
        simpleData: {
          enable: true,
          idKey: "id",
          pIdKey: "pId",
          rootPId: 0
        }
      }

    };

    //把树放进页面
    this.treeObj = $.fn.zTree.init($("#dictionaryManagerZTree"), setting, dics);
  }

  clickTree = (event, treeId, treeNode) =>{
    let dicId = $("#dicId");
    if(treeNode.id == dicId.val()){
      let selectedArray:Array<object> = this.treeObj.getSelectedNodes();
      if (selectedArray.length>0) {
        this.treeObj.cancelSelectedNode(selectedArray[0]);
      }
      dicId.val("");
    }else{
      dicId.val(treeNode.id);
    }
    this.search();
  }

  /**
   * yesOrNo格式化函数
   * @param value
   * @param row
   * @param index
   * @returns {any}
   */
  private yesOrNoFormat(value, row, index) {
    if (value == '1') {
      return '是';
    }
    if (value == '0') {
      return '否';
    }
  }

  add(){
    this.router.navigate(['add'], {relativeTo: this.route});
  }

  /**
   * 实现修改页面跳转
   */
  update() {
    let rows = this.table.bootstrapTable('getSelections');
    this.id = this.tableUtil.getCloumns(rows, "id");
    if (this.id.length == 1) {
      this.router.navigate(['update', {id: this.id[0]}], {relativeTo: this.route});
    }else {
      this.dialogService.modalInfo("请选择一条数据");
    }
  }

  dicDelete(){
    let rows = this.table.bootstrapTable('getSelections');
    this.id=this.tableUtil.getCloumns(rows,"id");
    if ( undefined == this.id || this.id.length == 0 ) {
      this.dialogService.modalInfo("请选择一条数据");
    } else {
      this.dialogService.modalInfoWithCancelBtn("确定删除？", this.requestDelete);
    }
  }

  private requestDelete = () =>{
    this.dictionaryService.deletesDD(this.id).subscribe(
      result => this.responseUtil.success(result, this.processDicDeleteResult),
      message => this.responseUtil.error(message)
    );

  }

  processDicDeleteResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.search();
      this.initDictionaryZTree();
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.modalInfo(result.message,()=>this.search());
    }
  }
}
